package com.star.security.authentication.wxapp;

import com.star.security.authentication.Authentication;
import com.star.security.authentication.AuthenticationProvider;
import com.star.security.authentication.wxapp.response.WxappLoginResponse;
import com.star.security.exception.AuthenticationException;
import com.star.security.user.UserDetails;
import com.star.security.user.UserDetailsService;

/**
 * 通过用户名密码验证
 *
 * @author yangzj
 */
public class WxappAuthenticationProvider implements AuthenticationProvider {

    private final UserDetailsService userDetailsService;
    private final WxappAuthenticationApi wxappAuthenticationApi;

    public WxappAuthenticationProvider(UserDetailsService userDetailsService, WxappAuthenticationApi wxappAuthenticationApi) {
        this.userDetailsService = userDetailsService;
        this.wxappAuthenticationApi = wxappAuthenticationApi;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 校验code
        Integer type = Integer.parseInt(authentication.getDetails().toString());
        WxappLoginResponse response = wxappAuthenticationApi.authenticate(authentication.getCredentials().toString(), type);
        UserDetails userDetails = userDetailsService.getByOpenId(response.getOpenId(), response.getUnionId(), type);
        return WxappAuthenticationToken.authenticated(userDetails, authentication.getExpiresIn());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return WxappAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
